<template>
  <div class="app-container" v-loading="pageLoading">
    <div>
      <el-tabs class="cententBox" v-model="activeName" @tab-change="handleClick">
        <el-tab-pane v-for="(item, key) in tabsList" :key="key" :label="item.value" :name="item.key">
          <div class="add-btn">
            <el-button class="buttonClass" size='medium' type="primary" @click="createItem" v-show="isSuper"
              :icon="Plus" circle />
          </div>
          <div style="padding:10px 120px;width:80%;overflow-y:auto">
            <template v-if="fieldsDesign.length">

              <z-Form :data="showData" :formProps="formProps" :fields="fieldsDesign">
                <template v-slot:formItem="curItem">
                  <div class="t-14" style="color:#999;margin:-10px 10px 25px">
                    {{ curItem.item.desc }} <span class="t-14 text-warning pointer" v-show="isSuper"
                      @click="clickEdit(curItem.item)">设置</span>
                  </div>
                </template>
              </z-Form>
            </template>
            <template v-else>
              <el-empty description="暂无参数，点击添加">
                <el-button type="primary" @click="createItem">添加</el-button>
              </el-empty>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="showTable ? fieldsDetail : fields"
      @submit="submit" :submitLoading="submitLoading" v-model="editFormVisible">
      <template v-slot:operation-left>
        <el-button v-if="showDelete" type="warning" v-show="isSuper" @click="deleteParam">删除</el-button>
      </template>
    </z-form-dialog>
    <el-dialog width="70%" :close-on-click-modal="false" v-model="showTable" @closed='closedDia' append-to-body>
      <div style="padding-left:120px">
        <div class="panel-info">
          <div class="panel-title">参数字段</div>
          <div class="panel-body">
            <el-tag class="mb-5 fr" type="info">提示：拖动表格行可进行排序</el-tag>
            <z-table ref="dragTable" v-if="listDetail.length" class="drag-Table" :list="listDetail"
              :tableProps="tablePropsDetail" :columns="columnsDetail">
              <template v-slot:content="v">
                <template v-if="v.key === 'ParamValueDesc'">
                  <el-input v-model="v.row['ParamValueDesc']"></el-input>
                </template>
                <template v-if="v.key === 'ParamValue'">
                  <el-input v-model="v.row['ParamValue']"></el-input>
                </template>
              </template>
              <template v-slot:operation="v">
                <a href="#" class="text-primary" v-if="v.$index == listDetail.length - 1"
                  @click.prevent="addDetailParam(v.row, v.index)" v-show="isSuper">新增</a>
                <a href="#" v-if="listDetail.length > 1" class="text-danger"
                  @click.stop.prevent="deleteDetailParam(v.row, v.$index)" v-show="isSuper">删除</a>
              </template>
            </z-table>
          </div>
        </div>
      </div>
      <div class="text-right mt-10">
        <el-button @click="showTable = false">关闭
        </el-button>
        <el-button type="primary" @click="submitDetailParam" :loading="submitLoading" v-show="isSuper">保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  Plus
} from '@element-plus/icons-vue'
</script>

<script>
import commonMixin from '@/views/_common/mixin'
import zForm from '@/views/_common/form.vue'
import _ from 'lodash'
import { useDraggable } from 'vue-draggable-plus'


export default {
  mixins: [commonMixin],
  components: { zForm },
  name: 'adminParamDesign',
  data: function () {
    return {
      api: this.$api.param,
      showDelete: false,
      apiCreate: this.$api.param + 'AddOrUpdateParamter',
      apiEdit: this.$api.param + 'UpdateParamterIni',
      initData: {
        ParamPriority: 0,
      },
      list: [],
      name: '系统参数',
      activeName: "1",
      listDetail: [],
      detailParams: {
        ParamValue: null,
        ParamValueDesc: null,
      },
      formProps: {
        dialogWidth: '70%',
        labelWidth: '220px',
        // title:null, //dialog title
      },
      columnsDetail: [
        { title: '名称', key: 'ParamValueDesc', hideTooltip: true },
        { title: '字段', key: 'ParamValue', hideTooltip: true },
      ],
      tablePropsDetail: {
        'highlight-current-row': true,
        border: true,
        opsColWith: '100',
        showIndexCol: true,
        rowKey: 'id',
      },
      fieldsDetail: [],
      fields: [
        { title: '参数模块', key: 'ParamModule', name: 'select', required: true, options: [] },
        { title: '参数代码', key: 'ParamName', required: true },
        { title: '展示名称', key: 'LabelDesc', required: true },
        {
          title: '展示类型',
          key: 'ParamInputType',
          name: 'select',
          required: true,
          props: {
            disabled: false,
          },
          options: [
            { key: 'input', value: '文本' },
            { key: 'number', value: '数字' },
            { key: 'switch', value: '是否' },
            { key: 'button', value: '多行文字' },
          ],
        },
        {
          title: '备注',
          key: 'Remarks',
          name: 'textarea',
          required: true,
          tips: '请尽可能的描述清楚此参数的作用，以及使用到的值所代表的含义',
        },
      ],
      fieldsDesign: [],
      // showFields: [],
      tableProps: {
        border: true,
        opsColWith: 120,
      },
      tabsList:[],
      showData: {},
      showTable: false,
      isSuper: true,
      query: {
        page: 1,
        size: 999,
      },
    }
  },
  computed: {},
  methods: {
    submitDetailParam() {
      if (this.listDetail.some((i) => !i.ParamValueDesc) || this.listDetail.some((i) => !i.ParamValue)) {
        this.$message.info('参数名称和字段均不能为空')
        return
      }
      this.submitLoading = true
      let data = this.listDetail.map((i, t) => {
        return {
          ...this.listDetail[0],
          ...i,
          ParameterId: i.ParameterId || 0,
          ParamPriority: t,
        }
      })
      this.http.post(this.api + 'RangeAddOrUpdateParams', data,).then((r) => {
        this.submitLoading = false
        this.$message.success('操作成功')
        this.showTable = false

      }).catch(e => {
        this.submitLoading = false
        
      })
    },
    addDetailParam() {
      this.listDetail.push({ ...this.listDetail[0], ParameterId: null, ParamValueDesc: null, ParamValue: null })
    },
    deleteDetailParam(row, index) {
      this.$confirm('确定要删除这条参数？').then(() => {
        if (row.ParameterId) {
          this.http.post(this.api + 'DeleteParameter', { ...row }).then((r) => {
            this.listDetail.splice(index, 1)
          })
        } else {
          this.listDetail.splice(index, 1)
        }
        this.$message.success('操作成功')
      })
    },
    closedDia() {
      this.getFileds(this.activeName)
    },
    deleteParam() {
      this.$confirm('确定要删除这条参数？').then(() => {
        this.http.post(this.api + 'DeleteParameter', this.data).then((r) => {
          this.editFormVisible = false
          this.getFileds(this.activeName)
        })
      })
    },
    submit() {
      let insertUrl = this.apiCreate
      let updateUrl = this.apiEdit
      let url = this.data.id ? updateUrl : insertUrl
      let data = this.formatBeforeSave(this.data)
      let check = this.validataData(this.fields, data)
      if (!check) return
      if (data.ParamInputType == 'switch') {
        data.ParamValue = '0'
      }
      this.submitLoading = true
      this.http.post(url, data)
        .then((r) => {
          this.editFormVisible = false
          this.getFileds(this.activeName)
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    handleClick() {
      this.getFileds(this.activeName)
    },
    createItem() {
      this.data = _.cloneDeep(this.initData)
      this.data.ParamModule = this.activeName
      this.editFormVisible = true
      this.showDelete = false
      let tmp = this.fields.find((i) => i.key == 'ParamInputType')
      if (!!tmp) {
        tmp.props.disabled = false
      }
    },
    clickEdit(item) {
      let tmp = this.fields.find((i) => i.key == 'ParamInputType')
      if (!!tmp) {
        tmp.props.disabled = true
      }
      this.showDelete = true
      this.http.get(this.api + `GetParameterById`, { Id: item.id }).then((r) => {
        r.ParamModule = r.ParamModule.toString()
        this.data = r
        this.editFormVisible = true
      })
    },
    getFileds(value) {

      this.http.get(this.api + `GetParamerIniByModule?module=${value}`).then((r) => {
        this.showData = {}
        this.fieldsDesign = []
        r.forEach((i) => {
          this.showData[i.ParamName] = i.ParamValue

          this.fieldsDesign.push({
            title: i.LabelDesc || '参数X',
            key: i.ParamName,
            name: i.ParamInputType,
            desc: i.Remarks,
            id: i.ParameterId,
            props: {
              activeValue: '1',
              inactiveValue: '0',
            },
            events: {
              change: () => {
                this.changeParam(i, i.ParamName)
              },
              click: () => {
                this.clickParam(i)
              },
            },
          })

        })
      })
    },
    changeParam(i, param) {
      let item = _.cloneDeep(i)
      item[param] = this.showData[param]
      let data = {}
      data = {
        ...item,
        ParamValue: this.showData[param],
      }
      this.http.post(this.api + 'AddOrUpdateParamter', data).then((r) => {
      })
    },
    clickParam(i) {
      if (i.ParamInputType != 'button') return
      this.listDetail = []

      this.http.get(this.api + 'GetParametersQuery', i).then((r) => {
        if (r.length == 1) {
          r[0].ParamValueDesc = r[0].ParamName
        }
        this.showTable = true
        this.listDetail = r
        this.$nextTick(() => {
          this.initSortable()
        })
      })
    },
    initSortable() {
      // 获取表格row的父节点
      const ele = this.$refs.dragTable.$el.querySelector('.el-table__body > tbody')
      useDraggable(ele, this.listDetail)

    },
  },
  created: function () {
    this.http.post(this.$api.dictionary, ['BASE_ParamsMoudle']).then((r) => {

      this.tabsList = r[0].data
      this.getFieldConfig('ParamModule').options = r[0].data
      console.log(this.getFieldConfig('ParamModule').options, '123')
    })
    // this.http.get(this.$api.user + 'checksuperuser').then((r) => {
    //   this.isSuper = r
    // })
    this.getFileds(this.activeName)
  },

}
</script>
<style scoped lang="scss">
.add-btn {
  position: fixed;
  right: 40px;
  bottom: 60px;
}

.buttonClass {
  width: 60px;
  height: 60px;
  padding: 0;

  i {
    font-size: 22px;
  }

}

:deep(.el-tabs--card) {
  height: calc(100vh - 110px);
  /* overflow-y: auto; */
}

:deep(.el-tab-pane) {
  height: calc(100vh - 110px);
  overflow-y: auto;
}

::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: #eee;
  border-radius: 3px;
}
</style>
